<?php

namespace App\Http\Controllers\Admin;

use App\Helpers\VideoParser;
use App\Library\Cms\PostItemTrait;
use App\Models\PostCatlog;
use App\Models\PostItem;
use Illuminate\Http\Request;

class PostController extends BaseController
{
    use PostItemTrait;
    /**
     * @return \Illuminate\Contracts\View\Factory|\Illuminate\Http\JsonResponse|\Illuminate\View\View
     * @throws \Psr\SimpleCache\InvalidArgumentException
     * @throws \Exception
     */
    public function index(){

        $this->assign([
            'title'=>'',
            'username'=>'',
            'catid'=>0,
            'status'=>'',
            'type'=>'',
            'time_begin'=>'',
            'time_end'=>'',
            'post_types'=>trans('post.post_types'),
            'post_status'=>trans('post.post_status'),
        ]);

        $queryParams = [];
        $query = PostItem::with('catlog');

        $title = $this->request->input('title');
        if ($title) {
            $queryParams['title'] = $title;
            $query = $query->where('title', 'LIKE', "%$title%");
        }

        $username = $this->request->input('username');
        if ($username) {
            $queryParams['username'] = $username;
            $query = $query->where('username', $username);
        }

        $catid = $this->request->input('catid');
        if ($catid) {
            $queryParams['catid'] = $catid;
            $catIds = PostCatlog::fetchAllChildIds($catid);
            $query = $query->whereIn('catid', $catIds);
        }

        $status = $this->request->input('status');
        if ($status != '') {
            $queryParams['status'] = $status;
            $query = $query->where('status', $status);
        }

        $type = $this->request->input('type');
        if ($type) {
            $queryParams['type'] = $type;
            $query = $query->where('type', $type);
        }

        $time_begin = $this->request->input('time_begin');
        if ($time_begin) {
            $queryParams['time_begin'] = $time_begin;
            $query = $query->where('created_at', '>', strtotime($time_begin));
        }

        $time_end = $this->request->input('time_end');
        if ($time_end) {
            $queryParams['time_end'] = $time_end;
            $query = $query->where('created_at', '<', strtotime($time_end));
        }

        $this->assign($queryParams);

        $items = $query->orderByDesc('aid')->paginate(20);
        $this->assign([
            'items'=>$items,
            'pagination'=>$items->appends($queryParams)->render(),
            'catlogOptions'=>PostCatlog::getOptions($catid)
        ]);

        return $this->view('admin.post.list');
    }

    /**
     * 移动文章
     */
    public function move(){
        $items = $this->request->post('items');
        $target = $this->request->post('target');
        if ($items) {
            foreach ($items as $aid) {
                PostItem::where('aid', $aid)->update(['catid'=>$target]);
            }
        }

        return ajaxReturn();
    }

    /**
     * 设置文章图片
     */
    public function setimage(){
        $aid = $this->request->input('aid');
        $image = $this->request->input('image');
        if ($aid && $image){
            PostItem::where('aid', $aid)->update(['image'=>$image]);
            return ajaxReturn();
        }else {
            return ajaxError(1, 'invalid parameter');
        }
    }

    /**
     * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View
     * @throws \Exception
     * @throws \Psr\SimpleCache\InvalidArgumentException
     */
    public function newpost(){

        $aid   = $this->request->get('aid');
        $catid = $this->request->get('catid');
        $type  = $this->request->input('type');
        $type  = in_array($type, array('image','video', 'voice')) ? $type : 'article';
        $this->assign([
            'aid'=>$aid,
            'catid'=>$catid,
            'type'=>$type,
            'item'=>[
                'aid'=>0,
                'type'=>$type,
                'catid'=>0,
                'created_at'=>date('Y-m-d H:i:s'),
                'title'=>'',
                'from'=>setting('sitename'),
                'fromurl'=>setting('siteurl'),
                'image'=>'',
                'alias'=>'',
                'allowcomment'=>'',
                'tags'=>'',
                'author'=>$this->username,
                'price'=>0,
                'summary'=>''
            ],
            'content'=>[
                'aid'=>0,
                'content'=>'',
                'created_at'=>time(),
                'updated_at'=>time()
            ],
            'images'=>[],
            'media'=>[],
        ]);

        if ($aid) {
            $item = PostItem::find($aid);
            if ($item) {
                $item->created_at = $item->created_at ? @date('Y-m-d H:i:s', $item->created_at) : @date('Y-m-d H:i:s');
                $item->type = in_array($item->type, ['image','video']) ? $item->type : 'article';
                $catid = $item->catid;
                $this->assign([
                    'type'=>$item->type,
                    'catid'=>$catid,
                    'item'=>$item
                ]);
            }

            $content = $item->content;
            if ($content) $this->assign(['content'=>$content]);

            $images = $item->images()->get();
            if ($images) $this->assign(['images'=>$images]);

            $media = $item->media;
            if ($media) $this->assign(['media'=>$media]);
        }

        $this->data['catlogOptions'] = PostCatlog::getOptions($catid);
        return $this->view('admin.post.newpost');
    }

    /**
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function save(Request $request){
        $post = $this->storePost($request);
        return ajaxReturn(['post'=>$post]);
    }

    /**
     * 批量删除
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function batchDelete(Request $request)
    {
        $items = $request->input('items');
        if (is_array($items))
        {
            PostItem::whereIn('aid', $items)->get()->map(function (PostItem $item){
                $item->delete();
            });
        }

        return ajaxReturn();
    }

    public function batchResolve(Request $request)
    {
        $items = $request->input('items');
        if (is_array($items))
        {
            PostItem::whereIn('aid', $items)->update(['status'=>1]);
        }

        return ajaxReturn();
    }

    public function batchReject(Request $request)
    {
        $items = $request->input('items');
        if (is_array($items))
        {
            PostItem::whereIn('aid', $items)->update(['status'=>0]);
        }

        return ajaxReturn();
    }

    public function batchMove(Request $request)
    {
        $target = $request->input('target');
        $items = $request->input('items');

        if (is_array($items))
        {
            PostItem::whereIn('aid', $items)->update(['catid'=>$target]);
        }

        return ajaxReturn();
    }

    protected function authenticateOwner()
    {
        return false;
    }
}
